package lyh.hnu.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import lyh.hnu.common.R;
import lyh.hnu.entity.po.User;
import lyh.hnu.service.UserService;
import lyh.hnu.utils.SMSUtils1;
import lyh.hnu.utils.ValidateCodeUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpServletRequest request) {
        //获取手机号
        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(phone)) {
            //生成随机4位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code:{}", code);

            //调用阿里云提供的短信服务API完成发送短信
            //SMSUtils1.sendMessage();

            //将生成的验证码存到Session中
            request.getSession().setAttribute(phone, code);
            return R.success("手机短信验证码发送成功");
        }
        return R.error("手机短信验证码发送失败");
    }


    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpServletRequest request) {
        //获取手机号
        String phone = map.get("phone").toString();
        //获取验证码
        String code = map.get("code").toString();
        //从Session中获取保存的验证码
        String codeInSession = request.getSession().getAttribute(phone).toString();
        //校对验证码
        if (codeInSession != null && codeInSession.equals(code)) {
            //如果能够校对成功，说明登录成功
            //判断是否为新用户，如果为新用户则自动完成注册
            User user = userService.lambdaQuery().eq(User::getPhone, phone).one();
            if (user == null) {
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            //log.info("id:{}", user.getId());
            request.getSession().setAttribute("user", user.getId());
            //log.info("值:{}", request.getSession().getAttribute("user").toString());
            return R.success(user);
        }
        return R.error("登录失败");
    }
}
